function ecog=ecogRemoveCommonAverageReference(ecog,type,weights)
% ecog=ecogRemoveCommonAverageReference(ecog) Removes the common average reference
%
% PURPOSE:  Subtracts from all channels in data the common average reference
%           (timepoint by timepoint average) calculated from the selected good
%           channels and stores it in refChanTS. Calculations are done
%           seperately for each trial.
%
% INPUT:
% ecog:     An ecog structure (maybe baseline corrected data?)
% type:     OPTIONAL. Defines the way a common signal is removed. DEFAULT
%               is 'equal'
%           'equal' equally weighted average over all channels subtracted
%           'projected' the projection on the average signal is subtracted
%           'predefined' removes the weighted average data
% weights:  weights for 'predefined.' It is a column vector of length =
%           number of channels
% OUTPUT:
% ecog:     An ecog structure with 'refChanTS holding the common average
%           refernce
%

% 090131 JR wrote it
% 110502 CC included options 'type' and weights
% 110601 CR removed zero mean over time step. This should be done outside
% this function

if nargin < 2
    type = 'equal';
end

switch type
    case 'equal'
        ecog.refChanTS=zeros(1,size(ecog.data,2),size(ecog.data,3));
        for k=1:size(ecog.data,3)
%            ecog.data=ecog.data-repmat(mean(ecog.data(:,:,k),2),1,size(eco
%            g.data,2)); %this step separate outside
            ecog.refChanTS(1,:,k)=mean(ecog.data(ecog.selectedChannels,:,k),1);
            ecog.data(:,:,k)=ecog.data(:,:,k)-repmat(ecog.refChanTS(1,:,k),size(ecog.data,1),1);
        end
    case 'projected'
        ecog.refChanTS=zeros(1,size(ecog.data,2),size(ecog.data,3));
        for k=1:size(ecog.data,3)
%              ecog.data=ecog.data-repmat(mean(ecog.data(:,:,k),2),1,size(e
%              cog.data,2)); %this step separate outside
             ecog.refChanTS(1,:,k)=mean(ecog.data(ecog.selectedChannels,:,k),1);
             normRef = norm(ecog.refChanTS(1,:,k));
             for m = 1:size(ecog.data,1)
                ecog.data(m,:,k) = ecog.data(m,:,k)-(dot(ecog.data(m,:,k), ecog.refChanTS(1,:,k))/normRef^2)*ecog.refChanTS(1,:,k);
             end    
        end
    case 'predefined'
        if nargin<3,
            error(['Weights not given']);
        else
            weights = weights/norm(weights);
            for k=1:size(ecog.data,3)
                ecog.data(:,:,k) = ecog.data(:,:,k)-(ecog.data(:,:,k)'*weights)';
            end
        end
    otherwise
        error(['Unknown option given:' type])
end
